package com.p6Map;

import java.util.*;
import java.util.stream.Collectors;

public class Test3 {
    private static final Set<User> USERS = create();

    public static void main(String[] args) {
        toMap(USERS);
    }

    private static Set<User> create() {
        User u1 = new User(1, "C1", User.CHENGDU);
        User u2 = new User(2, "C2", User.CHENGDU);
        User u3 = new User(3, "H3", User.HAERBIN);
        User u4 = new User(4, "H4", User.HAERBIN);
        Set<User> users = new HashSet<>();
        users.add(u1);
        users.add(u2);
        users.add(u3);
        users.add(u4);
        return users;
    }

    //基于流的方法实现
    private static void toMap(Set<User> users) {
        users.stream()
                //将用户按照城市分组并聚合
                .collect(Collectors.groupingBy(User::getCity))
                //Map不支持foreach语句直接循环遍历，但支持foreach的方法来遍历
                .forEach((city, us) -> {
                    System.out.println(city + ": ");
                    us.forEach(u -> System.out.println(u.getName()));
                });
    }
}
